$.fn.extend({
    /**
     * [tabFun 选项卡函数]
     * @param  {[type]} obj [tabClass:"选项卡当前项class名字"，content:"当前显示选项容器对象"]
     * @example:   $(".tab_param li").tabFun({tabClass:"active",content:$(".param_content")})
     */
    tabFun: function (obj) {
        /*
         obj = {tabClass:tabClassName,content: contentObject}
         */
        $(this).click(function () {
            var tabIndex = $(this).index();
            $(this).addClass(obj.tabClass).siblings().removeClass(obj.tabClass)
            obj.content.children().eq(tabIndex).show().siblings().hide();
        })
    },
    dataAttr: function (attrName, attrValue) {
        var str = $(this).attr('data-attr');
        var attrs = {};
        //console.log(str);
        if (str) {
            attrs = JSON.parse(str);
        }
        if (!attrValue && typeof (attrValue) === 'undefined') {
            //console.log(JSON.stringify(attrs));
            if (attrs === null || attrs[attrName] === null) {
                return null;
            }
            return attrs[attrName];
        } else {
            attrs[attrName] = attrValue;
            $(this).attr('data-attr', JSON.stringify(attrs));
        }
    },
    buttonAddToCart: function (tpl) {
        $(this).click(function(){
            $.addToCart(this , tpl);
        });
    },
    /**
     * 购买数量选择器
     * @params object params 
     * {
     *      min : 1
     *      max : 2
     *      selector
     * }
     * 格式 <a +><input v><a -> 要求元素前后 + - 号与input同级
     * @returns {undefined}
     */
    goodsNumSelector: function (params) {
        var _params = {
            min : 1,
            max : 6
        }
        for (var i in _params) {
            if (!!params[i]) {
                _params[i] = params[i];
            }
        }
        var input = $(this);
        input.val(1);
        $(this).prev().addClass('diabled').click(function () {
            if (input.val()>_params.min) {
                input.val(parseInt(input.val())-1);
            } 
            if (input.val()<=_params.min) {
                input.val(_params.min);
                $(this).addClass('disabled');
            }
        });
        $(this).next().click(function () {
            if (input.val()<_params.max) {
                input.val(parseInt(input.val())+1);
            } 
            if (input.val()>=_params.max) {
                input.val(_params.max);
                $(this).addClass('disabled');
            }
        });
    }
})

//wap请求的封装 
/**
 * 
 * @param path 
 * @param data 
 * @param cb callback function(data , code , message)
 * @param fcb failfunction (code , message)
 */
$.extend({
    "loadData": function (path, data, cb, fcb) {
        if (!fcb) {
            fcb = function (code, message) {
                alert(message);
            };
        }
        $.ajax({
            "url": path,
            "type": "POST",
            "dataType": "JSON",
            "data": data,
            "success": function (data) {
                if (typeof (data.code) === 'undefined') {
                    return fcb(-1, "请求失败");
                }
                if (data.code !== 0) {
                    return fcb(data.code, data.message);
                }
                return cb(data.data, data.code, data.message);
            }
        });
    } ,
    "__lastClickedCartBtn" : null,
    "addToCart" : function (obj) {
        if ($(obj).attr('lock') == true) {
            return;
        }
        $.__lastClickedCartBtn = obj;
        var imgSrc = $(obj).parents('li').find('img').attr('src');
        $('#addToCartLayer').remove();
        var goodsId = $(obj).dataAttr('goodsId');
        if (!goodsId) {
            return;
        }
//        goodsId = '50893';
        /**
         * 加入购物车
         * @param {type} goods
         * @param {type} callback
         */
        function doAddToCart (goods , callback) {
            $.loadData("/flow/cart/addProduct" , {'goods':JSON.stringify(goods)} , function (data) {
                callback();
            } , function (code,message) {
                alert(message);
            });
        }
        function closeLayer () {
            $(obj).dataAttr('lock',false);
            $('.quan_layer,.sc_layer').remove();
        }
        function showLayer () {
            $('.quan_layer,.sc_layer').show();
            $('.quan_layer .layer_close').click(closeLayer);
        }
        //成功后的动画事件
        function animateAfterSuccess (object, numberCount) {
            var _addCart = {
                '__cartRight': $('#_AD_right_shoppingcart'),//右侧购物车图标
                '__cartNum': numberCount,//购物车中的数量
                '__createImg': function () {
                    var addCartBtnOffset = $(object).offset(),
                        addCartBtnOffsetTop = addCartBtnOffset.top + 52,
                        addCartBtnOffsetLeft = addCartBtnOffset.left + 200;
                    var thumSrc = $('<img class="fly-img" style="display:block;z-index:9000;width: 50px;height: 50px;position: absolute;-webkit-border-radius: 10px;border-radius: 10px;" src="' + imgSrc + '">').css({
                        'top': addCartBtnOffsetTop - 60,
                        'left': addCartBtnOffsetLeft
                    }).hide()
                    $('body').append(thumSrc);
                    return thumSrc;
                },
                '__init':function(){
                    var that = this;
                    var scrollFunc = function (e) { // 这里为了防止加入购物车动画开始时，滚动鼠标而做的限制
                        e = e || window.event;
                        if (e && e.preventDefault) {
                            e.preventDefault();
                            e.stopPropagation();
                        } else {
                            e.returnvalue = false;
                            return false;
                        }
                    };
                    $('body').bind('mousewheel', function (e) {
                        if (scrollFunc) {
                            scrollFunc(e);
                        }
                    });
                    $('body').bind('DOMMouseScroll', function (e) {
                        if (scrollFunc) {
                            scrollFunc(e);
                        }
                    });
                    var thumSrc = that.__createImg.call(object).show();
                    thumSrc.animate({
                        'top': that.__cartRight.offset().top - 20,
                        'left': that.__cartRight.offset().left + 8,
                        'width': 20,
                        'height': 20,
                        'opacity': .5
                    }, 'slow').animate({
                        'top': that.__cartRight.offset().top + 20,
                        'left': that.__cartRight.offset().left + 16,
                        'z-index': 1,
                        'width': 5,
                        'height': 5,
                        'opacity': 0
                    }, 'slow', function () {
                        thumSrc.remove();
                        var i = $('#cart_num_2').text();
                        $('#cart_num_2').text(i?parseInt(i)+numberCount:numberCount);
                        $('body').unbind('mousewheel');
                        $('body').bind('DOMMouseScroll');
                    });
                }
            }         
            _addCart.__init();
        }
        //加载购物车图层
        $.loadData('/flow/cart/goodsAddBar' , {"goodsId":goodsId} , function (data) {
            if (!window.Stock) {$('body').append('<script src="/themes/ugo/js/2016/stock.js"></script>');}
            closeLayer();
            $('body').append(data.html);
            //公共渲染部分
            var mapping = data.mapping; //mapping{productId:[colorId,styleId]}
            if (!mapping) {
                return;
            }
            var params = []; //初始化库存请求数据
            for (var i in data.mapping) {
                params.push({"product_id":i,"goods_id":goodsId,"amt":1});
            }
            var autoClick = false;//自动点击提交
            if (params.length == 1) {
                autoClick = true;
            }
            var stocks = window.Stock.getStock(params);
                //初始化各个按钮
            $('span[data-role="color-item"]').click(function () {
                //已选中或不可选时,不触发
                if ($(this).hasClass('nogoods') || $(this).hasClass('select')) {
                    return;
                }
                $('span[data-role="color-item"]').removeClass('select');
                $(this).addClass('select');
                $('span[data-role="style-item"]').addClass('nogoods').removeClass('enable');
                var colorId = $(this).dataAttr('colorId');
                for (var product_id in mapping) {
                    if (mapping[product_id][0] != colorId) {//颜色不匹配
                        continue;
                    }
                    if (stocks[product_id].stock <= 0) { //无货不可选
                        continue;
                    }
                    $('#style-'+mapping[product_id][1]).removeClass('nogoods').addClass('enable');
                }
                if ($('li.enable[data-role="style-item"]').length == 1) {
                    $('li.enable[data-role="style-item"]').addClass('select');
                } 
            });
            $('li[data-role="style-item"]').click(function(){
                if ($(this).hasClass('nogoods') || $(this).hasClass('select')) {
                    return;
                }
                $('li[data-role="style-item"]').removeClass('select');
                $(this).addClass('select');
            });
                
            //选中第一个有货的商品实现选中
            for (var i in stocks) {
                if (stocks[i].stock>0) {
                    var pid = stocks[i].product_id;
                    if (!mapping[pid]) { continue; } //将优惠商品的颜色尺码置为可选状态
                    //设置颜色属性的可选状态
                    $("span[data-role='color-item']").each(function(){
                        if ($(this).dataAttr('colorId') == mapping[pid][0]) {
                            $(this).removeClass('nogoods').addClass('enable');
                        }
                    });
                    $("span[data-role='style-item']").each(function(){
                        if ($(this).dataAttr('styleId') == mapping[pid][1]) {
                            $(this).removeClass('nogoods').addClass('enable');
                        }
                    });
                }
            }
            if ($("span.enable[data-role='color-item']").length === 1) {
                $("span.enable[data-role='color-item']").addClass('select');
                if ($("span.enable[data-role='style-item']").length === 1) {
                    $("span.enable[data-role='style-item']").addClass('select');
                }
            }
            //绑定加入购物车按钮点击
            $('#btn-add-cart').click (function () {
                var layer = $(this).parents('.quan_layer');
                var style= layer.find('span.select[data-role="style-item"]');
                var color= layer.find('span.select[data-role="color-item"]');
                if (style.length<1 || color.length<1) { 
                    if (autoClick == false) {
                        alert("请选择商品的规格");
                    }
                    return;
                }
                var params = {
                    "goods_id" : goodsId , 
                    "product_id" : null ,
                    "number" : 1
                }
                for (var productId in mapping) {
                    if (mapping[productId][0] == color.dataAttr('colorId') 
                            && mapping[productId][1]==style.dataAttr('styleId')) {
                        params.product_id = productId;
                    }
                }
                if (!params.product_id || params.number <1) {
                    alert("商品信息有误,请稍后再试!");
                    return;
                }
                
                if (autoClick == false) {
                    $.__lastClickedCartBtn = $('#btn-add-cart');
                }
                doAddToCart(params , function () {
                    animateAfterSuccess($.__lastClickedCartBtn,1);
                    closeLayer();
                });
            });
            if (autoClick == true) {
                $('#btn-add-cart').trigger('click');
            } else {
                showLayer();
            }
        });
    } 
});